package com.caopeng.javaee.controller;

import com.caopeng.javaee.entity.course;
import com.caopeng.javaee.entity.student;
import com.caopeng.javaee.service.CourseService;
import com.caopeng.javaee.service.CourseStudentService;
import com.caopeng.javaee.service.ExcelService;
import com.caopeng.javaee.service.StudentService;
import com.caopeng.javaee.util.ExcelImportUtils;
import net.bytebuddy.description.method.ParameterList;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: javaee
 * @description: 课程的逻辑处理
 * @author: caopeng
 * @create: 2018-12-09 18:40
 **/
@Controller
public class CourseController {
    @Autowired
    CourseService courseService;
    @Autowired
    StudentService studentService;
    @Autowired
    CourseStudentService courseStudentService;
    @Autowired
    ExcelService excelService;
    @RequestMapping(value = "modified_course")
    public String modified_course(int course_code, Model model, HttpSession session){
        course mycourse=courseService.CfindById(course_code);
        int student_number=courseStudentService.Courseidfindstudentlist(course_code).size();
        String nowpeople=mycourse.coursePeopleLimit;
        System.out.println("现在学生上限人数"+nowpeople);
        System.out.println("该科学生数目"+student_number);
        System.out.println(mycourse.getId());
        session.setAttribute("course_id",mycourse.getId());
        model.addAttribute("thecourse",mycourse);
        model.addAttribute("thecoursenumber",student_number);
        model.addAttribute("nowpeople",nowpeople);
        return "course_content";
    }
    @PostMapping(value = "rename")
    public @ResponseBody String rename(HttpServletRequest request, HttpSession session,Model model){
        int courseid=(int)session.getAttribute("course_id");
        String text=request.getParameter("text");
        System.out.println("course_id"+session.getAttribute("course_id")+"text"+text);
        course thecourse=courseService.CfindById(courseid);
        thecourse.setcourseName(text);
        courseService.Csave(thecourse);
        return text;
    }
    @PostMapping(value = "add_student")
    public @ResponseBody String add_student(String student_account,String student_name,HttpSession session){
        //System.out.println("student_account"+student_account);
        //System.out.println("student_name"+student_name);
        student thestudent=studentService.SfindByAccountAndName(student_account,student_name);
        if(thestudent==null) {
            return "false";
        }
        else{
            int student_id=thestudent.getId();
            int course_id=(int)session.getAttribute("course_id");
            String test=courseStudentService.CourseAddStudent(course_id,student_id);
            System.out.println("test"+test);
        }
        return "yes";
    }
    @PostMapping(value = "batchImport")
    public  @ResponseBody String batchImport(@RequestParam(value="filename") MultipartFile file,
                                                         HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {
        String text="";
        //ajax返回字符串不能带有双引号不然返回就是页面了
        //判断文件是否为空
        System.out.println("进入了方法 batchImport");
        if(file==null){
            session.setAttribute("msg","文件不能为空！");
            text="error";
        }

        //获取文件名
        String fileName=file.getOriginalFilename();

        //验证文件名是否合格
        if(!ExcelImportUtils.validateExcel(fileName)){
            session.setAttribute("msg","文件必须是excel格式！");
            text="error";
        }

        //进一步判断文件内容是否为空（即判断其大小是否为0或其名称是否为null）
        long size=file.getSize();
        if(StringUtils.isEmpty(fileName) || size==0){
            session.setAttribute("msg","文件不能为空！");
            text="error";
        }

        //批量导入
        String course_id=String.valueOf(session.getAttribute("course_id"));
        String message = excelService.batchImport(fileName,file,course_id);
        session.setAttribute("msg",message);
        text="success";
        return text;
    }
    @GetMapping(value = "ouputexcel")
    public @ResponseBody String ouputexcel( HttpSession session,HttpServletResponse response){
//        System.out.println("进图ouputexcel方法");
        String []headers={"课程名字","学生姓名"};
        int course_id=(int)session.getAttribute("course_id");
        String course_name=courseService.CfindById(course_id).getcourseName();
        System.out.println("打印课程名字"+course_name);
        //先查询出学生id然后再是学生name
        List<String> listname=courseStudentService.Courseidfindstudent(course_id);
      //  System.out.println("打印长度获得名字的"+listname.size());
        //获得到了数据开始写excel的片段
        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFSheet sheet=workbook.createSheet();
        sheet.setDefaultColumnWidth((short)18);
        HSSFRow row=sheet.createRow(0);
        for(short i=0;i<headers.length;i++)
        {
            HSSFCell cell=row.createCell(i);
            HSSFRichTextString text=new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        int index=1;
        for(;index<=listname.size();index++)
        {
            HSSFRow row1=sheet.createRow(index);
            row1.createCell(0).setCellValue(course_name);
            row1.createCell(1).setCellValue(listname.get(index-1));
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + course_name+".xlsx");
        try {
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        }catch (IOException e)
        {
            e.printStackTrace();
        }
        return "yes";
    }
    /**
    * @Description: 添加学生的界面，分页用的
    * @Param: [model, start, size, session]
    */
    @RequestMapping(value = "dataAddStudent")
    public String dataAddStudent(Model model, @RequestParam(value = "start", defaultValue = "0") int start, @RequestParam(value = "size", defaultValue = "5") int size,@RequestParam(value = "studentname",defaultValue = "%") String studentname,HttpSession session)throws Exception{

        start = start < 0 ? 0 : start;
        //Sort sort = new Sort(Sort.Direction.ASC, "");
        Pageable pageable = new PageRequest(start, size);
        session.setAttribute("studentname",studentname);
        String courseid=session.getAttribute("course_id").toString();
        System.out.println("studentname"+studentname);
        Page<student> page= studentService.ScourseselectStudent(courseid,studentname,pageable);
        model.addAttribute("page", page);
        model.addAttribute("studentname",studentname);
        return "courseAddStudent";
    }
    /**
    * @Description: 主要处理checkbox添加学生，的逻辑部分
    * @Param:
    */
    @PostMapping(value = "dataAddStudentLogic")
    public @ResponseBody String dataAddStudentLogic(HttpSession session,HttpServletRequest request)
    {
        //tostring 获得是字符串
        String course_id=session.getAttribute("course_id").toString();
        String data=request.getParameter("final");
        String ArrayStudent[]=data.split(",");
        List studentlist=new ArrayList<student>();
        student temstudent;
        for(int i=0;i<ArrayStudent.length;i++)
        {
            System.out.println(ArrayStudent[i]);
            temstudent=studentService.SfindById(ArrayStudent[i]);
            studentlist.add(temstudent);
        }
        courseStudentService.insetStudent(studentlist,course_id);
        System.out.println("dataAddStudentLogic 批量添加结束");
        return "yes";
    }
    @PostMapping(value = "savePeopleLimit")
    public @ResponseBody String savePeopleLimit(HttpSession session,HttpServletRequest request){
        int request_numebr=Integer.valueOf(request.getParameter("limit_number"));
        System.out.println("request_number"+request_numebr);
        int course_id=(int)session.getAttribute("course_id");
        System.out.println("course_id"+course_id);
        int nownubmer=courseStudentService.Courseidfindstudentlist(course_id).size();
        if(request_numebr>=nownubmer) {
            course thiscourse=courseService.CfindById(course_id);
            thiscourse.setCourse_prople_limit(String.valueOf(request_numebr));
            courseService.Csave(thiscourse);
            System.out.println("保存成功");
            return "yes";
        }
        else{
            return "error";
        }
    }
}

